package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.User;

public class LoginFilter implements Filter {
	
	private String[] ignorURL;
	
	public boolean isIgnore(HttpServletRequest request) {
		String path=request.getRequestURI().toLowerCase();
		for(String ignore:ignorURL) {
			if(path.contains(ignore)) {
				return true;
			}
		}
		return false;
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		
		//
		if(isIgnore(request)){
			chain.doFilter(req, res);
			return;
		}
		
		//
		HttpSession session = request.getSession();
		User loginUser = (User) session.getAttribute("loginUser");

		if (loginUser == null) {
			String path = session.getServletContext().getContextPath();
			response.sendRedirect(path + "/login");
			return;
		}
		chain.doFilter(req, res);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.ignorURL = config.getInitParameter("ignorUrl").split(",");
	}

}
